package com.lingx.web.core.urihanlder;

import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Component;

import com.lingx.service.LingxService;
import com.lingx.service.ReportService;
import com.lingx.utils.Utils;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.QueryStringDecoder;
@Component
public class ExcelHandler implements IUriHandler {
	@Resource
	private ReportService reportService;
	@Resource
	private LingxService lingxService;
	@Override
	public String getUri() {
		return "/excel";
	}

	@Override
	public void handler(ChannelHandlerContext ctx, FullHttpRequest request) {
		try {
			QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.uri());
			Map<String,List<String>> map=queryStringDecoder.parameters();

			String ecode=map.get("ecode").get(0);
			String userId=map.get("userid").get(0);
		String sql=	reportService.getSqlBySession(ecode, userId);
		int index=sql.toLowerCase().lastIndexOf(" limit ");
		if(index!=-1){
			sql=sql.substring(0,index);
		}

		sql+=" limit "+lingxService.getConfigValue("lingx.grid.excel.limit", "10000") ;
		//System.out.println("Excel:"+sql);
		XSSFWorkbook excel=reportService.createExcelBySQL(sql,ecode, null);
		ByteArrayOutputStream bos=new ByteArrayOutputStream (); 
		 excel.write(bos);
		 int  length=bos.size();
		FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
		Unpooled.wrappedBuffer(bos.toByteArray()));
		response.headers().set("Content-Disposition", "attachment;filename=" + Utils.getTime()+".xlsx");
		response.headers().set("Content-Length", Integer.toString(length));
		response.headers().set("Content-Type", "application/vnd.ms-excel;charset=gb2312");
		response.headers().set("Access-Control-Allow-Origin", "*");
		response.headers().add("Access-Control-Allow-Methods", "GET,POST");
		ctx.writeAndFlush(response);
		}catch(Exception e) {
			e.printStackTrace();
		}
	}

}
